﻿using UnityEngine;

public class FrameManager {
	// === Public =====================================================================================================
	public static FrameManager CreateInstance() {
		var instance = new FrameManager();
		return instance;
	}

	public void Create(GameObject ownerParent) {
		_fieldSize = SettingsLevelModel.FieldSize;
		CreateThisParent(ownerParent);
		CreateFrame();
	}

	public void Destroy() {
		Managers.Element.DestroyElements(Tools.Element.GetElements(FieldElementType.Frame));
		Object.Destroy(_parent);
	}

	// === Private ====================================================================================================
	private Vector2 _fieldSize;
	private GameObject _parent;

	private void CreateThisParent(GameObject ownerParent) {
		_parent = new GameObject("Frame");
		_parent.transform.parent = ownerParent.transform;
	}

	private void CreateFrame() {
		CreateTopPartOfTheFrame();
		CreateBottomPartOfTheFrame();
		CreateLeftPartOfTheFrame();
		CreateRightPartOfTheFrame();
	}

	private void CreateTopPartOfTheFrame() {
		for (int index = 0; index <= _fieldSize.x; index++) {
			var pointX = index - 1;
			var pointY = _fieldSize.y;
			CreateElement(new Vector3(pointX, 0, pointY));
		}
	}

	private void CreateBottomPartOfTheFrame() {
		for (int index = 0; index <= _fieldSize.x; index++) {
			var pointX = index;
			var pointY = -1;
			CreateElement(new Vector3(pointX, 0, pointY));
		}
	}

	private void CreateLeftPartOfTheFrame() {
		for (int index = 0; index <= _fieldSize.y; index++) {
			var pointX = -1;
			var pointY = index - 1;
			CreateElement(new Vector3(pointX, 0, pointY));
		}
	}

	private void CreateRightPartOfTheFrame() {
		for (int index = 0; index <= _fieldSize.y; index++) {
			var pointX = _fieldSize.x;
			var pointY = index;
			CreateElement(new Vector3(pointX, 0, pointY));
		}
	}

	private void CreateElement(Vector3 position) {
		Managers.Element.CreateElement(FieldElementType.Frame, position, _parent);
	}
}